package com.chalk.util.logistics;

import com.chalk.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author xiaoqiang
 * @Description 阿里物流工具类
 * 参考文档 https://market.aliyun.com/products/56928004/cmapi021863.html?spm=5176.2020520132.101.3.2cb77218oY9TMF#sku=yuncode1586300000
 * @date 2019/5/20 14:55
 */
@Component
public class AliLogisticsUtil {
    // 请求地址
    private final static  String URL = "https://wuliu.market.alicloudapi.com/kdi";

    @Value("${aliyun.logistics.appcode}")
    private String APPCODE;

    /**
     * 获取物流信息
     * @param no 订单号
     * @param type 快递公司简写
     * @return
     */
    public String getLogisticsInfo(String no, String type){
        String urlSend = URL+ "?no=" + no + "&type=" + type;
        try {
            URL geturl = new URL(urlSend);
            HttpURLConnection httpURLConnection = (HttpURLConnection) geturl.openConnection();
            httpURLConnection.setRequestProperty("Authorization", "APPCODE " + APPCODE);//格式Authorization:APPCODE (中间是英文空格)
            //int httpCode = httpURLConnection.getResponseCode();
            /* status 0:正常查询 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号 */
            String json = read(httpURLConnection.getInputStream());
            return json;
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }


    /*
        读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

}
